/**
 * 租金变更页签相关事件
 */
 import ampub from 'ampub';
 import fa from 'fa';
 import { ajax, toast } from 'nc-lightapp-front';
 import { getUsufructAssetTab } from '.';
 import constants from '../../constants/index';
 import { doRefresh, editPreCheck, filterDeletedRows, getCardtableData, lockcards, saveAfter } from './headButtonClick';
 import { setBodyBtnsEnable } from './setStatus';
 
 
 const { fa_components: { AccbookAndPeriod: { getAccbooksAndPeriods } } } = fa;
 const {
     utils: { multiLangUtils: { getMultiLangByID }, msgUtils: { showMessage } },
     components: { LoginContext: { loginContextKeys, getContext } }
 } = ampub;
 const {
     assetDataSource,
     URL,
     UISTATE,
     LEASECHANGEFIELD: leaseChangeField,
     MODAL_ID: { LeaseChangeModal },
     CARD_BTNS: { TABLE_BODY, TABLE_HEAD, TABLE_HEAD: { LEASE_CHANGE_TAB, LEASE_CHANGE_TAB: { ADD_LINE, DELETE_LINE } } },
     AREA: {
         CARD: {
             USEDEPT_TAB: usedept_tab,
             BASIC_INFO_AREA: basicInfoForm,
             LEASE_CHANGE_TAB: lease_change_tab,
             USUFRUCTASSET_AREA: usufructassetForm,
             STEPRENTSTANDARD_TAB: steprentstandard_tab,
             ASSET_ALL: assetAllArea
         }
     }
 } = constants;
 
 export default function(props, id) {
     switch (id) {
         //增行
         case ADD_LINE:
             doAddLine.call(this);
             break;
 
         //删行
         case DELETE_LINE:
             doDeleteLine.call(this);
             break;
 
         default:
             break;
     }
 }
 
 function doAddLine() {
     const { props: { editTable } } = this;
     editTable.addRow(lease_change_tab);
 }
 
 function doDeleteLine() {
     const { props, props: { editTable, form } } = this;
 
     let rowsWillDel = editTable.getCheckedRows(lease_change_tab);
     let indexs = rowsWillDel.map((row) => row.index);
     /* 按阶梯租金计租 */
     let step_lease_flag = form.getFormItemsValue(basicInfoForm, 'step_lease_flag').value;
     if (step_lease_flag === true) {
         if (indexs.includes(0)) {
             /* 国际化： "201201504A-0000104": "按阶梯租金计租，不允许删除第一行阶梯租金！" */
             showMessage(props, { content: getMultiLangByID('201201504A-0000104'), color: 'warning' });
             return false;
         }
     }
 
     editTable.deleteTableRowsByIndex(lease_change_tab, indexs);
     setBodyBtnsEnable(this.props, lease_change_tab);
 }
 
 function showEvent() {
     const { props: _props, props: { editTable, modal, form } } = this;
     const pk_card = this.curr_pk_card;
 
     /* 卡片主键不存在 */
     if (!pk_card) {
         return;
     }
 
     //卡片校验通过，可以编辑
     let locking = () => {
         /* 对卡片进行加锁 */
         lockcards.call(this, 'lock').then(() => {
             openLeaseChangeModal.call(this);
         });
     };
 
     //租赁变更校验
     return editPreCheck.call(this).then(locking, (err) => {
         showMessage(_props, {
             content: (err && err.message) || err || getMultiLangByID('201201504A-000013'),
             color: 'danger'
         });
     });
 }
 
 /**
  * 打开租赁变更页面
  */
 function openLeaseChangeModal() {
     const { props: _props, props: { editTable, modal, form } } = this;
     const pk_card = this.curr_pk_card;
     let pk_accbook = this.state.currentPkaccbook;
     let bodyTabDataManager = this.bodyTabDataManager;
 
     //先查询一下租金标准然后赋值到租赁变更页签上
     bodyTabDataManager.getTabVOs(pk_card, pk_accbook, steprentstandard_tab).then((bodyvos) => {
         //先组装数据，然后将数据渲染到打开的组件上
         assemblyData.call(this, JSON.parse(JSON.stringify(bodyvos)));
         modal.show(LeaseChangeModal, {
             beSureBtnClick: beSureEvent.bind(this),
             cancelBtnClick: closeEvent.bind(this),
             closeModalEve: closeEvent.bind(this)
         });
         // 阶梯租金赋值
         editTable.setTableData(lease_change_tab, JSON.parse(JSON.stringify(bodyvos)));
         stepRentPlanBtnsControl.call(this);
     });
 }
 
 /**
  * 处理阶梯租金标准表格的操作按钮
  */
 function stepRentPlanBtnsControl() {
     const { props: { editTable, form } } = this;
     let step_rent = form.getFormItemsValue(basicInfoForm, 'step_rent').value;
     updateBtnDisabled.call(this, step_rent);
 }
 
 //阶梯租金标准
 function updateBtnDisabled(visibleBtns = false) {
     const { props: { button, editTable } } = this;
     button.setButtonDisabled(Object.values(LEASE_CHANGE_TAB), !visibleBtns);
     if(visibleBtns){
         /* 删行按钮默认禁用 */
         button.setButtonDisabled([ DELETE_LINE ], true);
     }
     editTable.setStatus(lease_change_tab, UISTATE.EDIT);
 
     // 资产租入合同，禁止编辑阶梯租金
     if (this.bill_source_4A3A) {
         // 资产租入合同，禁止编辑
         editTable.hideColByKey(lease_change_tab, 'opr');
         editTable.setStatus(lease_change_tab, UISTATE.BROWSE);
         button.setButtonDisabled(Object.values(LEASE_CHANGE_TAB), true);
     }
 }
 
 function cancelEvent() {
     const { props: { modal } } = this;
     lockcards.call(this, 'unlock');
     resetLeaseChange.call(this);
     //清空计算数据
     this.leaseChangeDiffData = {};
     this.leaseChangeNewData = {};
     this.leaseChangeOldData = {};
     modal.close(LeaseChangeModal);
 }
 
 function closeEvent() {
     cancelEvent.call(this);
     doRefresh(this);
 }
 
 function beSureEvent() {
     const { props: { modal } } = this;
     let isContinue = check.call(this);
     if (!isContinue) {
         return;
     }
     let flag = compareData.call(this);
     if (!flag) {
         toast({
             color: 'warning',
             content: getMultiLangByID('201201504A-000064') /*国际化处理：租赁变更没有任何变化！*/
         });
         cancelEvent.call(this);
         return;
     }
     //组装数据到后台进行变更
     leaseChangeEvent.call(this);
 }
 
 //组装旧数据
 function assemblyData(bodyvos) {
     const { props: { form } } = this;
     let leaseChangeOldData = {};
     const rows = getUsufructAssetTab.call(this);
     leaseChangeField.forEach((field) => {
         //生效日期默认为空
         if ('change_date' == field) {
             let businessDate = getContext(loginContextKeys.businessDate);
             leaseChangeOldData[field] = { value: businessDate };
         } else if ('steprentStandardData' == field) {
             leaseChangeOldData[field] = bodyvos;
         } else {
             const [ { values: { [field]: { value: filed_value, display: display_value } } } ] = rows;
             //其他值从使用权资产上直接取
             leaseChangeOldData[field] = {
                 value: filed_value,
                 display: display_value
             };
         }
     });
     this.leaseChangeOldData = leaseChangeOldData;
     //将旧值拷贝一份留给新值
     this.leaseChangeNewData = JSON.parse(JSON.stringify(leaseChangeOldData));
 }
 
 function check() {
     const {
         leaseChangeNewData: {
             rent_standard,
             step_rent,
             change_date,
             renewal_flag,
             relet_ending_date,
             purchase_choice,
             purchase_price,
             ending_date
         }
     } = this;
     /* 生效日期 */
     if (!change_date.value) {
         toast({
             color: 'danger',
             content: getMultiLangByID('201201504A-000083') /*国际化处理：生效日期不允许为空！*/
         });
         return false;
     }
     /* 续租截止期 */
     if (renewal_flag.value) {
         if (!relet_ending_date) {
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-000084') /*国际化处理：续租截止期不允许为空！*/
             });
             return false;
         }
     }
     /* 购买价格 */
     if (purchase_choice.value) {
         if (!purchase_price) {
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-000085') /*国际化处理：购买价格不允许为空！*/
             });
             return false;
         }
     }
     /* 租赁截止期 */
     if (!ending_date.value) {
         toast({
             color: 'danger',
             content: getMultiLangByID('201201504A-000089') /*国际化处理：租赁截止期不允许为空！*/
         });
         return false;
     }
     /* 阶梯租金 */
     if (!step_rent.value) {
         /* 租金标准 */
         if (!rent_standard.value) {
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-000094') /*国际化处理：租金标准不能为空！*/
             });
             return false;
         }
     }else{
         let result = checkLeaseChangeTab.call(this);
         if(!result){
             return false;
         }
     }
 
     return true;
 }
 
 /**
  * 校验阶梯租金必输项，与卡片的阶梯租金不是一个areaid
  */
  function checkLeaseChangeTab(){
     const { props, props: { form, editTable } } = this;
     
     editTable.filterEmptyRows(lease_change_tab, ['start_date']);
 
     let steprentstandardrows = editTable.getNumberOfRows(lease_change_tab);
     if (!steprentstandardrows || steprentstandardrows.length == 0) {
         toast({
             color: 'error',
             content: getMultiLangByID('201201504A-0000111') /*国际化处理：请录入阶梯租金标准！*/
         });
         return false;
     }
 
     editTable.selectAllRows(lease_change_tab,true);
     const rows = editTable.getCheckedRows(lease_change_tab);
     let checkRows = rows.map((item,index,arr)=>{
         return item.data;
     });
 
     // reverseSelected 反选
     //阶梯租金标准
     let tab_check = editTable.checkRequired(lease_change_tab, checkRows);
     if (!tab_check) {
         return false;
     }
     
     return true;
 }
 
 /**
  * 比较变更前后数据是否有变化
  */
 function compareData() {
     const { props: { editTable, form } } = this;
     let { leaseChangeOldData, leaseChangeNewData } = this;
 
     /* 对比前重置变更基本信息；依赖差异数据 */
     resetLeaseChange.call(this);
     /* 清空差异数据 */
     this.leaseChangeDiffData = {};
     //是否有变化的标识
     let isChanged = false;
 
     let fieldOfNumber = [
         'interest_rate', //年折现率
         'rent_standard', //租金标准
         'tax_rate', //税率
         'purchase_price' //购买价格
     ];
 
     leaseChangeField.forEach((field) => {
         //生效日期不做比较
         if ('change_date' == field) {
             return;
         } else if ('steprentStandardData' == field) {
             //过滤空行
             editTable.filterEmptyRows(lease_change_tab, [ 'start_date' ], 'except');
             let bodyExist = editTable.getChangedRows(lease_change_tab);
             if (bodyExist.length) {
                 isChanged = true;
                 leaseChangeNewData[field] = editTable.getAllData(lease_change_tab);
                 //阶梯标准不记录具体数值，跟需求确认了
                 this.leaseChangeDiffData[field] = {
                     oldValue: null,
                     newValue: null
                 };
             } else {
                 // 删除不存在的数据，只有阶梯租金是特殊处理
                 leaseChangeNewData[field] = leaseChangeOldData[field];
                 delete this.leaseChangeDiffData[field];
             }
         } else if (fieldOfNumber.includes(field)) {
             if (!isEqualNumber(leaseChangeOldData[field].value, leaseChangeNewData[field].value)) {
                 isChanged = true;
                 form.setFormItemsValue(basicInfoForm, {
                     [field]: leaseChangeNewData[field]
                 });
                 //只记录变化的数据传到后台
                 this.leaseChangeDiffData[field] = {
                     oldValue: leaseChangeOldData[field].value,
                     newValue: leaseChangeNewData[field].value
                 };
             }
         } else {
             //如果新旧值不相等
             if (!isEqual(leaseChangeOldData[field].value, leaseChangeNewData[field].value)) {
                 isChanged = true;
                 form.setFormItemsValue(basicInfoForm, {
                     [field]: leaseChangeNewData[field]
                 });
                 //只记录变化的数据传到后台
                 this.leaseChangeDiffData[field] = {
                     oldValue: leaseChangeOldData[field].value,
                     newValue: leaseChangeNewData[field].value
                 };
             }
         }
     });
     if (isChanged) {
         //如果存在变更，需要将生效日期赋值给使用权资产实体
         form.setFormItemsValue(basicInfoForm, {
             change_date: leaseChangeNewData.change_date
         });
     }
     return isChanged;
 }
 
 /**
  * 租赁变更失败后恢复数据；依赖差异数据
  */
 function resetLeaseChange() {
     const { leaseChangeOldData, leaseChangeDiffData, leaseChangeNewData, props: { form } } = this;
     const keys = Object.keys(leaseChangeDiffData);
     keys.forEach((field) => {
         if ([ 'steprentStandardData' ].includes(field)) {
             return;
         }
         form.setFormItemsValue(basicInfoForm, {
             [field]: leaseChangeOldData[field]
         });
     });
 }
 
 function leaseChangeEvent() {
     const that = this;
     const { props, props: { form } } = this;
     //组装用于提交到后台的数据
     this.syncDataForCommit();
     //获取多使用部门数据
     let usedeptData = getCardtableData.call(that, usedept_tab);
     //后台是先删除之前的然后再重新插入
     usedeptData = filterDeletedRows(usedeptData);
 
     let assetvos = Object.values(this.assetDataMap);
     //组装提交数据：按照一主多子的格式
     let data = {
         pageid: this.state.pageCode,
         templateid: this.templateid,
         userjson: this.leaseChangeDiffData,
         heads: [
             {
                 pageid: this.state.pageCode,
                 model: {
                     areacode: assetAllArea,
                     areaType: 'table',
                     rows: assetvos
                 }
             }
         ],
         bodysMap: {
             [usedept_tab]: {
                 pageid: that.state.pageCode,
                 model: {
                     areacode: usedept_tab,
                     rows: usedeptData,
                     areaType: 'table'
                 }
             },
             //使用权资产
             [usufructassetForm]: {
                 pageid: this.state.pageCode,
                 model: {
                     areacode: usufructassetForm,
                     rows: getUsufructAssetTab.call(this),
                     areaType: 'table'
                 }
             },
             //租金标准
             [steprentstandard_tab]: {
                 pageid: this.state.pageCode,
                 model: {
                     areacode: steprentstandard_tab,
                     rows: this.leaseChangeNewData.steprentStandardData.rows,
                     areaType: 'table'
                 }
             }
         }
     };
 
     // 补充使用权资产关联fa_card.pk_card
     const { heads: [ { model: { rows: [ { values: { pk_card: { value: pk_card } } } ] } } ] } = data;
     data.bodysMap[usufructassetForm].model.rows[0].pk_card = pk_card;
 
     const leaseChange = new Promise((resolve, reject) => {
         ajax({
             url: URL.LEASECHANGE,
             data,
             success: (res) => {
                 let { success, data } = res;
                 if (success && data) {
                     resolve(data);
                     return;
                 }
                 reject(data);
             },
             error: (err) => {
                 reject(err);
             }
         });
     });
 
     // 变更成功后刷新数据
     leaseChange.then(
         (data) => {
             toast({
                 color: 'success',
                 content: getMultiLangByID('201201504A-000065') /*国际化处理：租赁变更成功！*/
             });
             /* 下面顺序不可改变 */
             cancelEvent.call(this);
             saveAfter(this, data, false, false, true);
             doRefresh(that);
         },
         (err) => {
             showMessage(props, { color: 'danger', content: (err && err.message) || err });
         }
     );
 }
 
 //非number 类型的比较
 function isEqual(a, b) {
     if (isEmpty(a) && isEmpty(b)) {
         return true;
     }
     return a == b;
 }
 
 //number 类型的比较
 function isEqualNumber(a, b) {
     if (isEqualZero(a) && isEqualZero(b)) {
         return true;
     } else if (isEqualZero(a)) {
         return false;
     } else if (isEqualZero(b)) {
         return false;
     } else {
         let fa = Number.parseFloat(a);
         let fb = Number.parseFloat(b);
         return Math.abs(fa - fb) < Number.EPSILON;
     }
 }
 
 function isEmpty(a) {
     let emptyVal = [ null, undefined, '' ];
     return emptyVal.includes(a);
 }
 
 function isEqualZero(a) {
     if (isEmpty(a)) {
         return true;
     }
     try {
         let fa = Number.parseFloat(a);
         return Math.abs(fa) < Number.EPSILON;
     } catch (e) {}
 }
 
 export { showEvent, updateBtnDisabled };
 
 
